package com.appspot.yttv.client;

import java.util.ArrayList;
import java.util.List;

import com.appspot.yttv.client.JsonRequest.JsonRequestHandler;
import com.appspot.yttv.client.MediaRss.Entry;
import com.appspot.yttv.client.model.Playlist;
import com.appspot.yttv.client.model.Video;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.user.client.rpc.AsyncCallback;

/**
 * Generates playlists given a list of urls pointing to gdata video feeds.
 *  
 * @author Ramona Bobohalma
 */
public class FeedPlaylistProvider implements PlaylistProvider{
	
	private final List<String> sourceUrls;
	
	public FeedPlaylistProvider(List<String> sourceUrls) {
		this.sourceUrls = sourceUrls;
	}
	
	/**
	 * Gets a playlist from the provider.
	 * 
	 * This may involve server communication, or similar, so the interface is
	 * asynchronous.
	 * 
	 * @param callback Callback to notify with the playlist.
	 */
	public void getPlaylist(final AsyncCallback<Playlist> callback) {
		
		AsyncCallback<List<Video>> addToPlaylist = new AsyncCallback<List<Video>>() {
			Playlist playlist = new Playlist();
			int callbackNumber = 0;
			int totalCallbackNumber = sourceUrls.size();
			
			public void onSuccess(List<Video> list) {
				playlist.addAll(list);
				if (++callbackNumber >= totalCallbackNumber) {
					playlist.shuffle();
					callback.onSuccess(playlist);
				}
			}
			public void onFailure(Throwable caught) {
				if (++callbackNumber >= totalCallbackNumber) {
					playlist.shuffle();
					callback.onSuccess(playlist);
				}
			}
		};
		
		for (String url: sourceUrls) {
			getFeed(url,addToPlaylist);
		}
	}
	
	public void getFeed(String feedUrl, final AsyncCallback<List<Video>> callback) {
		JsonRequest.get(feedUrl,
				new JsonRequestHandler() {
					public void onRequestComplete(JavaScriptObject json) {
						MediaRss rss = json.cast();
						List<Video> list = new ArrayList<Video>();
						
						for (int i = 0, length = rss.getEntryLength(); i< length;  i++) {
							Entry entry = rss.getEntry(i)	;
							list.add(new Video(entry.getId(), entry.getTitle(), entry.getChannel()));	
						}
						callback.onSuccess(list);
					}
			});	
	}
}
